<template>
  <div>
    <a-card :bordered="false">
      <a-row justify="space-between" type="flex">
        <a-col :md="16" :sm="24">
          <ride-view
              ref="rideView"
              :card="card"
              :ride="ride"
              :during-second="duringSecond"
              :loading="loading">
            <span slot="extra">
              <a @click="queryInfo" style="margin-right: 16px">
                <a-icon type="redo"/>
                刷新
              </a>
            </span>
          </ride-view>
        </a-col>
        <a-col :md="7" :sm="24">
          <bike-cost/>
        </a-col>
      </a-row>
    </a-card>
    <a-card :bordered="false" style="margin-top: 18px"
            v-if="station.stationId === null || station.stationId === undefined">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="站点名称">
                <a-input v-model="queryParam.stationName" placeholder=""/>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
                        <span class="table-page-search-submitButtons">
                          <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                          <a-button style="margin-left: 8px" @click="() => queryParam = {}">重置</a-button>
                        </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <s-table
          ref="table"
          size="default"
          rowKey="key"
          :columns="columns"
          :data="loadData"
          showPagination="auto"
      >
      <span slot="action" slot-scope="text, record">
        <template>
          <a @click="handleListCar(record)">查看车辆</a>
          <a-divider type="vertical"/>
          <return-ride
              :station="record"
              :bike-number="ride === null || ride === undefined ? '' : ride.bikeNumber"
              :disabled="ride === null || ride === undefined"
              @success="handleSuccess"
          />
        </template>
      </span>
      </s-table>
    </a-card>
    <a-card :bordered="false" style="margin-top: 18px" v-else>
      <div class="table-page-search-wrapper">
        <a-descriptions>
          <a-descriptions-item label="站点名称">{{ station.stationName }}</a-descriptions-item>
          <a-descriptions-item label="站点信息">{{ station.note }}</a-descriptions-item>
        </a-descriptions>
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="车辆编号">
                <a-input v-model="queryParam2.stationName" placeholder=""/>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="车辆状态">
                <a-select v-model="queryParam2.bikeState" placeholder="请选择">
                  <a-select-option v-for="(state, i) in bikeStates" :key="i">
                    {{ state }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <span class="table-page-search-submitButtons">
                <a-button type="primary" @click="$refs.table2.refresh(true)">查询</a-button>
                <a-button style="margin-left: 8px" @click="() => queryParam2 = {}">重置</a-button>
                <a-button
                    type="primary"
                    style="margin-left: 8px"
                    @click="handleBack">
                  <a-icon type="left"/>
                  返回
                </a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <s-table
          ref="table2"
          size="default"
          rowKey="key"
          :columns="columns2"
          :data="loadData2"
          showPagination="auto"
      >
      <span slot="bikeState" slot-scope="text">
        <a-tag :color="text | stateColorFilter">{{ text | stateTextFilter }}</a-tag>
      </span>
      <span slot="action" slot-scope="text, record">
        <template>
          <rent-ride
              ref="rentRide"
              :bike-id="record.bikeId"
              :bike-number="record.bikeNumber"
              :station="station"
              :disabled="disabled || record.bikeState !== 0"
              @success="handleSuccess"/>
        </template>
      </span>
      </s-table>
    </a-card>
  </div>
</template>

<script>
import {queryCard} from '@/api/bike/card'
import BikeCost from "@/views/dashboard/BikeCost";
import {STable} from "@/components";
import {queryStation} from "@/api/system/station";
import moment from "moment";
import {queryRide} from "@/api/bike/ride";
import RentRide from "./modules/ride/RentRide";
import ReturnRide from "./modules/ride/ReturnRide";
import RideView from "./modules/ride/RideView";
import {listBikeByStation} from "@/api/basic/bike";

let that
let stateMap = {
  0: {
    text: '未使用',
    color: 'blue'
  },
  1: {
    text: '使用中',
    color: 'yellow'
  },
  2: {
    text: '维修中',
    color: 'grey'
  },
  3: {
    text: '报废',
    color: 'red'
  },
}

export default {
  name: 'RideList',
  components: {
    RentRide,
    ReturnRide,
    BikeCost,
    RideView,
    STable,
  },
  data () {
    return {
      card: null,
      ride: null,
      loading: true,
      duringSecond: 0,
      queryParam: {},
      queryParam2: {},
      station: this.$route.query,
      title: '',
      disabled: true,
      bikeStates: ['未使用', '使用中', '维修中', '报废',],
      columns: [
        {
          title: '站点名称',
          dataIndex: 'stationName',
          align: 'center',
        },
        {
          title: '站点信息',
          dataIndex: 'stationInfo',
          align: 'center'
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          scopedSlots: {customRender: 'action'}
        }
      ],
      loadData: parameter => {
        // 统一处理查询参数，便于后端表格DTO用固定参数接收
        const queryJson = {'queryParam': JSON.stringify(this.queryParam)}
        return queryStation(Object.assign(parameter, queryJson))
            .then(res => {
              return res.result
            })
      },
      columns2: [
        {
          title: '车辆编号',
          dataIndex: 'bikeNumber',
          align: 'center',
        },
        {
          title: '车辆状态',
          dataIndex: 'bikeState',
          sorter: true,
          align: 'center',
          scopedSlots: {customRender: 'bikeState'},
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          scopedSlots: {customRender: 'action'}
        }
      ],
      loadData2: parameter => {
        this.queryParam2.stationId = this.station.stationId
        const queryJson = {'queryParam': JSON.stringify(this.queryParam2)}
        return listBikeByStation(Object.assign(parameter, queryJson))
            .then(res => {
              return res.result
            })
      },
    }
  },
  beforeCreate () {
    that = this
  },
  created () {
    this.queryInfo()
  },
  filters: {
    stateTextFilter (state) {
      if (stateMap[state] === undefined) {
        return ''
      }
      return stateMap[state].text
    },
    stateColorFilter (state) {
      if (stateMap[state] === undefined) {
        return ''
      }
      return stateMap[state].color
    },
  },
  // beforeRouteEnter (to, from, next) {
  //
  // },
  // beforeRouteUpdate (to, from, next) {
  //
  // },
  watch: {
    $route (to, from) {
      this.station = this.$route.query
      this.$nextTick(() => {
        if (this.station.stationId !== null && this.station.stationId !== undefined) {
          this.handleOk2()
        } else {
          this.handleOk()
        }
      })
    },
  },
  methods: {
    handleApply () {
      this.$refs.addCard.add(this.card)
    },
    handleLose () {
      this.$refs.loseCard.lose(this.card)
    },
    queryInfo () {
      this.loading = true
      this.card = null
      this.ride = null
      this.disabled = true
      this.queryCardInfo().then(res => {
        this.card = res
        if (this.card !== null && this.card.cardState === 0) {
          return this.queryRideInfo()
        }
        this.loading = false
      }).then(res => {
        this.ride = res
        if (this.ride !== null) {
          this.duringSecond = moment(this.ride.serverTime).diff(moment(this.ride.gmtCreate), 'second')
          this.$refs.rideView.setTimer()
        }
        this.loading = false
        if (this.ride === null && this.card.balance > 0) {
          this.disabled = false
        }
      }).catch(err => {
        this.loading = false
      })
    },
    queryCardInfo () {
      return new Promise(resolve => {
        queryCard().then(res => {
          if (res.message === 'success') {
            resolve(res.result)
          }
        }).catch(err => {
          console.log(err)
          this.$message.error(err.result || '查询租借卡信息失败')
        })
      })
    },
    queryRideInfo () {
      return new Promise(resolve => {
        queryRide().then(res => {
          if (res.message === 'success') {
            resolve(res.result)
          }
        }).catch(err => {
          console.log(err)
          this.$message.error(err.result || '查询用户骑行信息失败')
        })
      })
    },
    handleListCar (record) {
      this.$router.push({path: '/bike/ride', query: record})
    },
    handleBack () {
      this.$router.go(-1)
    },
    handleOk () {
      this.$refs.table.refresh(false)
    },
    handleOk2 () {
      this.$refs.table2.refresh(false)
    },
    handleSuccess () {
      this.queryInfo()
    },
  }
}
</script>

<style scoped>

</style>
